import 'package:homepad/iot/basic_types.dart';
import 'package:homepad/iot/message_def.dart';
import 'package:homepad/logger/logger.dart';
import 'light_onoff.dart';

class LightDimmer extends LightOnOff {
  LightDimmer.fromJson(super.json) : super.fromJson();

  @override
  String get desc {
    if (!reachable) {
      return super.desc;
    }
    return onOff ? "$lightness%" : "关";
  }

  var lightness = 20;
  void setLightness(int value) {
    if (!onOff) {
      setOnOff(true);
    }

    logger.info("lightness: $value");
    lightness = value;
    delegate.onAttributeSet(
        AttributePathIB(
            endpoint: endpointId,
            cluster: ClusterIds.levelControl,
            attribute: LevelControlAttributeIds.currentLevel),
        (value.toDouble() * 255 / 100).toInt());
  }

  @override
  void readAllState() {
    super.readAllState();
    super.readAttribute(ClusterIds.levelControl, LevelControlAttributeIds.currentLevel);
  }

  @override
  bool onAttributeReport(AttributePathIB path, data) {
    if (path.cluster != ClusterIds.levelControl) {
      return super.onAttributeReport(path, data);
    }

    if (path.attribute == LevelControlAttributeIds.currentLevel) {
      var newValue = ((data as int).toDouble() * 100 / 255).toInt();
      if (newValue == lightness) {
        return false;
      }
      logger.debug("newValue=$newValue");
      lightness = newValue;
      return true;
    }
    return false;
  }
}
